/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MathLib.HashMatrix;

import java.util.ArrayList;

/**
 *
 * @author mark_o
 */
public class Xoleckuj {
    HashMatrix U;
    public Xoleckuj(IMatrix matrix){
        int n = matrix.getN();
    	U = new  HashMatrix(HashMatrix.HASH_TYPE, n);
        for (int i = 0; i < n; i++) {
            /*double temp = 0.0;
            ArrayList<Integer> rowIndexes = matrix.getJRowIndex(i);
            ArrayList<Double> rowValues = matrix.getJRowValues(i);
            int k =0;
            while((k<rowValues.size())&&(rowIndexes.get(k)<i)){
            temp+= Math.pow(rowValues.get(k),2.0);
            k++;
            }*/
            double temp = 0.0;
    		for (int k = 0; k < i; k++) {
    			temp+=U.getValue(k,i)*U.getValue(k,i);
    		}

            U.setValue(i, i, Math.sqrt(matrix.getValue(i, i) - temp));

            for (int j = i+1; j < n; j++) {
    			temp = 0.0;
    			for (int z = 0; z < i; z++) {
        			temp+=U.getValue(z, i)*U.getValue(z, j);
        		}
    			try{
                    U.setValue(i, j, (matrix.getValue(i, j)-temp)/U.getValue(i, i));
    			}catch(Exception e){
    				System.out.println("еррор бл*");
    			}
    		}
        }

        /*for(int i=0;i<5;i++){
        for(int j=0;j<5;j++){
        System.out.print(U.getValue(i, j)+"\t");
        }
        System.out.print("\n");
        }*/


    }

    public double[] calculate(double[] b) {
        for(int i=0;i<U.getN();i++){
        for(int j=0;j<U.getN();j++){
        System.out.print(U.getValue(i, j)+"\t");
        }
        System.out.print("\n");
        }
        int n = U.getN();
        double[] y = new double[n];
    		for(int i=0;i<n;i++){
    			double temp=0;
    			for (int k = 0; k < i-1; k++) {
        			temp+=U.getValue(k, i)*y[k];
        		}
    			y[i] = (b[i]-temp)/U.getValue(i, i);
    		}

        for(int j=0;j<U.getN();j++){
            System.out.print(y[j]+"\t");
        }

    	double[] x = new double[n];
    		for (int row = (U.getN()-1); row>=0; row--){
               double e = 0.0;
               ArrayList<Integer> indexes = U.getJRowIndex(row);
               ArrayList<Double> values = U.getJRowValues(row);
               for (int i=0; i<indexes.size(); i++){
                   e += x[indexes.get(i)]*values.get(i);
               }
               x[row] = (y[row]-e)/U.getValue(row,row);
            }
        return x;
    }
    

}
